YUI.add('wffilter', function (Y) {
	var filterInput = Y.one('.search-input');
	var clearSearch = Y.one('#clear-search');
	
	var history = new Y.HistoryHash();
	
	clearSearch.on('click',function(e){
		e.preventDefault();
		filterInput.set('value','');
		history.addValue('q',null);
	});
	
	Y.on('history:change', function (e) {
		  var changed = e.changed,
		      removed = e.removed;
		  if (changed.q) {
			  Y.filterProject(changed.q.newVal);
		  } else if (removed.q) {
			  Y.filterProject(null);
		  }
		  
		  if (changed.item) {
			  Y.entryItem(changed.item.newVal);
		  } else if (removed.item) {
			  Y.entryItem(null);
		  }
		  
	});
	
	var someItemData;
	var someItemDataHash;
	
	Y.entryItem = function(mid){
		if(mid){
			Y.rootEntry = mid;
			someItemData = Y.totalData.filter.filter(function(item){
				if(item.getValue('path').indexOf(mid) != -1){
					return true;
				}else{
					return false;
				}
			});
			
			someItemData.plug(Y.Plugin.RecordsetFilter);
			someItemData.plug(Y.Plugin.RecordsetIndexer);
			someItemDataHash = someItemData.indexer.createTable('uuid');
			Y.someItemData = someItemData;
			Y.someItemDataHash = someItemDataHash;
		}else{
			Y.rootEntry = 'nop';
			Y.someItemData = null;
			Y.someItemDataHash = null;
			someItemData = Y.totalData;
			someItemDataHash = Y.totalDataHash;
		}
		Y.resetLocalData(someItemData.get('records'));
	};
	
	Y.filterProject = function(phrase){
		var subset;
		if(phrase){
			subset = someItemData.filter.filter(function(item){
				if(item.getValue('title').indexOf(phrase) != -1 || item.getValue('note').indexOf(phrase) != -1){
					return true;
				}else{
					return false;
				}
			});
		}else{
			Y.resetLocalData(someItemData.get('records'));
			return;
		}
		var filteredSet = new Y.Recordset();
		filteredSet.plug(Y.Plugin.RecordsetIndexer);
		var tmpHolder = filteredSet.indexer.createTable('uuid');
		subset.each(function(item){
			if(!tmpHolder[item.getValue('uuid')])filteredSet.add(item);
			var pitem = someItemDataHash[item.getValue('dp')];
			//搜索根目录界定
			while(pitem){
				if(!tmpHolder[pitem.getValue('uuid')])filteredSet.add(pitem);
				pitem = someItemDataHash[pitem.getValue('dp')];
			}
		});
	
		subset.each(function(item){
			someItemData.filter.filter(function(titem){
				if(titem.getValue('path').indexOf(item.getValue('uuid')) != -1){
					if(!tmpHolder[titem.getValue('uuid')])filteredSet.add(titem);
				}
			});
		});
		Y.resetLocalData(filteredSet.get('records'));
	};
	
	filterInput.on('valueChange',function(e){
		if(e.newVal){
			history.addValue('q',e.newVal);
		}else{
			history.addValue('q',null);			
		}
		
	});
},'0.0.1',{requires:['node','base','event','highlight']});